package com.example.photography.Activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.donkingliang.imageselector.utils.ImageSelector;
import com.example.photography.R;
import com.example.photography.adapter.PhotoPublishAdapter;
import com.example.photography.bean.Product_bean;
import com.example.photography.common.BaseActivity;
import com.example.photography.common.Constant;
import com.example.photography.retrofit.ApiService;
import com.example.photography.retrofit.net.exception.ApiException;
import com.example.photography.retrofit.net.exception.ErrorConsumer;
import com.example.photography.retrofit.net.response.ResponseTransformer;
import com.example.photography.util.OnRecyclerItemClickListener;
import com.example.photography.util.SharePreference;
import com.example.photography.util.UIUtils;
import com.example.photography.util.Util;
import com.example.photography.util.WXTouchHelper;
import com.example.photography.view.LoadingDialog;
import com.example.photography.view.Message_Dialog;
import com.example.photography.view.ZFlowLayout;

import com.google.android.material.bottomsheet.BottomSheetDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bingoogolapple.swipebacklayout.BGAKeyboardUtil;
import dagger.hilt.android.AndroidEntryPoint;
import io.reactivex.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import static com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade;
import static com.example.photography.util.UIUtils.List_to_String;

/**
 * 用户发布照片作品
 */
@AndroidEntryPoint
public class Photo_Publish extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.product_title)
    EditText productTitle;
    @BindView(R.id.product_content)
    EditText productContent;
    @BindView(R.id.zv_groups)
    ZFlowLayout zvGroups;
    @BindView(R.id.ll_group)
    LinearLayout llGroup;
    @BindView(R.id.tv_publish)
    TextView tvPublish;
    @BindView(R.id.ll_item)
    LinearLayout llItem;
    @BindView(R.id.rc_photo)
    RecyclerView rcPhoto;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.tv_delete)
    TextView tvDelete;
    private PhotoPublishAdapter photoPublishAdapter;
    private static final int REQUEST_CODE = 0x00000011;
    private List<String> imgSelected = new ArrayList<>();
    private ItemTouchHelper itemTouchHelper;
    private Message_Dialog mMyDialog;
    private String title, content = null;
    private BottomSheetDialog sheelt;
    private List<String> groups_select = new ArrayList<>();
    //注入动态代理实例对象
    @Inject
    ApiService apiService;
    @Override
    protected void initData() {
        setPermission();
        initView();
        getHistory();
        initListen();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return true;//拦截返回键
        }
        return super.onKeyDown(keyCode, event);

    }

    public void exit() {
        title = productTitle.getText().toString().trim();
        content = productTitle.getText().toString().trim();
        if (!title.isEmpty() || !content.isEmpty() || imgSelected.size() > 0) {
            showDialog();
        } else {
            removeCurrentActivity();
        }
    }

    private void initListen() {
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                exit();
            }
        });
        llGroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bundle bundle = new Bundle();
                bundle.putStringArrayList("groups", (ArrayList<String>) groups_select);
                goToActivityForResult(Group_Search.class, 222, bundle);
            }
        });
        tvPublish.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("CheckResult")
            @Override
            public void onClick(View view) {
                add_product();
            }
        });
        /**
         * 如果没有scrollView包裹 则不用传入scrollView
         */
        WXTouchHelper myCallBack = new WXTouchHelper(photoPublishAdapter, imgSelected, scrollView, 70);
        itemTouchHelper = new ItemTouchHelper(myCallBack);
        itemTouchHelper.attachToRecyclerView(rcPhoto);
        rcPhoto.setAdapter(photoPublishAdapter);
        photoPublishAdapter.setData(imgSelected);
        rcPhoto.addOnItemTouchListener(new OnRecyclerItemClickListener(rcPhoto) {
            @Override
            public void onItemClick(RecyclerView.ViewHolder viewHolder) {//单击
                if (viewHolder.getAdapterPosition() == imgSelected.size()) {//点击添加图片
                    addimage();
                } else {//点击已添加的图片
                    long itemId = viewHolder.getAdapterPosition();
                    setImage(imgSelected.get((int) itemId));
                    Util.showToast(Photo_Publish.this, String.valueOf(itemId));

                }
            }

            //长按事件中开启拖拽 需要判断position不是+号图片
            @Override
            public void onLongClick(RecyclerView.ViewHolder viewHolder) {//长按
                if (viewHolder.getAdapterPosition() != imgSelected.size()) {
                    BGAKeyboardUtil.closeKeyboard(Photo_Publish.this);
                    itemTouchHelper.startDrag(viewHolder);
                }
            }

            @Override
            public void onOtherClick(MotionEvent e) {//空白区域监听

            }
        });

        myCallBack.setDragListener(new WXTouchHelper.DragListener() {
            @Override
            public void deleteState(boolean delete) {
                if (delete) {
                    tvDelete.setAlpha(0.8f);
                    tvDelete.setText("松手即可删除");
                } else {
                    tvDelete.setAlpha(0.5f);
                    tvDelete.setText("拖到此处删除");
                }
            }

            @Override
            public void dragState(boolean start) {
                if (start) {
                    tvDelete.setVisibility(View.VISIBLE);
                } else {
                    tvDelete.setVisibility(View.GONE);
                }
            }

            @Override
            public void clearView() {
                fixBottom();
            }

            @Override
            public void deleteOk() {

            }
        });

    }

    @SuppressLint("CheckResult")
    private void add_product() {
        //开启等待动画
        LoadingDialog.getInstance(this).show();
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        //参数类型
        MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
        for (String path : imgSelected) {
            File file = new File(path);
            builder.addFormDataPart("products", file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file));
        }
        builder.addFormDataPart("id_unique", Constant.UID);
        builder.addFormDataPart("title", productTitle.getText().toString().trim());
        builder.addFormDataPart("content", productContent.getText().toString().trim());
        builder.addFormDataPart("label", String.valueOf(List_to_String(groups_select)));
        MultipartBody multipartBody = builder.build();

        apiService.add_product(multipartBody)
                .compose(ResponseTransformer.obtain())
                .subscribe(new Consumer<Product_bean>() {
                    @Override
                    public void accept(Product_bean product_bean) throws Exception {
                        //正常情况下处理数据回调
                        LoadingDialog.getInstance(Photo_Publish.this).dismiss();
                        Util.showToast(getApplicationContext(),"发布成功，正在跳转请稍后~");
                        Bundle bundle = new Bundle();
                        bundle.putString("product_id",product_bean.getProduct_id());
                        goToActivity(Product_Content.class,bundle);
                        removeCurrentActivity();
                    }
                }, new ErrorConsumer() {
                    @Override
                    protected void error(ApiException e) {
                        Log.i("test1", "e=" + e.getErrorMsg());
                        LoadingDialog.getInstance(Photo_Publish.this).dismiss();
                        Util.showToast(getApplicationContext(), "发布失败："+e.getErrorMsg());
                    }
                });

    }

    private void initView() {
        tvTitle.setText("发布作品");
        photoPublishAdapter = new PhotoPublishAdapter(rcPhoto, 9);
        rcPhoto.setAdapter(photoPublishAdapter);
    }

    public void history_view() {
        if (title != null) {
            productTitle.setText(title);
        }
        if (content != null) {
            productContent.setText(content);
        }
        photoPublishAdapter.setData(imgSelected);
        fixBottom();
        initHistory(groups_select);
//       rcPhoto.notifyAll();
    }

    private void setPermission() {
        int hasWriteExternalPermission = ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (hasWriteExternalPermission == PackageManager.PERMISSION_GRANTED) {
            //预加载手机图片。加载图片前，请确保app有读取储存卡权限
            ImageSelector.preload(this);
        } else {
            //没有权限，申请权限。
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0x00000012);
        }

    }

    private void setImage(String url) {//展开图片//todo 单击图片消失,手势放大缩小功能待实现
        View view = getLayoutInflater().inflate(R.layout.full_image, null);
        ImageView imageView = view.findViewById(R.id.image);//获取diolog里面的返回键和确定键
        //加载网络图片
        Glide.with(this)
                .load(url)
                .transition(withCrossFade()) //Glide提供淡如淡出
                .into(imageView);
        mMyDialog = new Message_Dialog(this, 0, 0, view, R.style.DialogTheme);
//        让自定义dialog的宽度充满整个屏幕
        WindowManager windowManager = this.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = mMyDialog.getWindow().getAttributes();
        lp.width = (int) (display.getWidth()); //设置宽度
        mMyDialog.getWindow().setAttributes(lp);
        mMyDialog.show();
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mMyDialog.dismiss();
            }
        });
    }

    private void addimage() {
        ImageSelector.builder()
                .useCamera(true) // 设置是否使用拍照
                .setSingle(false)  //设置是否单选
                .setMaxSelectCount(9) // 图片的最大选择数量，小于等于0时，不限数量。
                .setSelected((ArrayList<String>) imgSelected) // 把已选的图片传入默认选中。
                .canPreview(true) //是否可以预览图片，默认为true
                .start(this, REQUEST_CODE); // 打开相册
    }



    /**
     * 处理recyclerView下面的布局
     * 添加删除时，处理下面布局比上面变化快的问题
     */
    private void fixBottom() {
        // TODO: 2021/5/16 以后修改这里，如果下面的组件没到底部就设置在底部，如果超过底部就动态调整
        int row = photoPublishAdapter.getItemCount() / 3;
        row = (0 == photoPublishAdapter.getItemCount() % 3) ? row : row + 1;//少于3为1行
        row = (4 == row) ? 3 : row;//最多为三行

        int width = Util.getScreenWidth(this);
        int itemWidth = (int) (width - getResources().getDimension(R.dimen.dimen_60)) / 3;//item宽高
        int itemSpace = (int) getResources().getDimension(R.dimen.dimen_10);//item间隔
        int marginTop = (itemWidth * row
                + itemSpace * (row - 1)
                + 80);


        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) llItem.getLayoutParams();
        params.setMargins(0, marginTop, 0, 0);
        llItem.setLayoutParams(params);
    }

    public void showDialog() {
        sheelt = new BottomSheetDialog(this);
        View contentView = LayoutInflater.from(this).inflate(R.layout.bottom_save, null);
        sheelt.setContentView(contentView);
        //给布局设置透明背景色
        sheelt.getWindow().findViewById(R.id.design_bottom_sheet).setBackgroundResource(android.R.color.transparent);
        sheelt.show();
        RelativeLayout rl_save = contentView.findViewById(R.id.rl_save);
        RelativeLayout rl_leave = contentView.findViewById(R.id.rl_leave);
        RelativeLayout rl_dismiss = contentView.findViewById(R.id.rl_dismiss);

        rl_dismiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sheelt.dismiss();//消失
            }
        });
        rl_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                save();
                removeCurrentActivity();
            }
        });
        rl_leave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharePreference.cleanHistory("publish_photo");
                removeCurrentActivity();
            }
        });
    }

    //保存草稿
    public void save() {
        // 获取搜索框信息
        SharedPreferences sharedPreferences = UIUtils.getContext().getSharedPreferences("publish_photo", 0);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("title", productTitle.getText().toString().trim());
        editor.putString("content", productContent.getText().toString().trim());
        editor.putString("photos", String.valueOf(List_to_String(imgSelected)));
        editor.putString("groups", String.valueOf(List_to_String(groups_select)));
        editor.apply();
    }

    //读取草稿
    public void getHistory() {
        // 获取搜索记录文件内容
        SharedPreferences sp = UIUtils.getContext().getSharedPreferences("publish_photo", 0);
        title = sp.getString("title", "");
        content = sp.getString("content", "");
        String photos = sp.getString("photos", null);
        // 用逗号分割内容返回数组
        if (photos != null && !photos.equals("")) {
            imgSelected.addAll(Arrays.asList(photos.split(",")));
        }
        String groups = sp.getString("groups", null);
        // 用逗号分割内容返回数组
        if (groups != null && !groups.equals("")) {
            groups_select.addAll(Arrays.asList(groups.split(",")));
        }
        history_view();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //防止窗体泄漏
        if (mMyDialog != null) {
            mMyDialog.dismiss();
        } else if (sheelt != null) {
            sheelt.dismiss();
        }
    }

    private void initHistory(List<String> datas) {
        ViewGroup.MarginLayoutParams layoutParams = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(10, 10, 10, 10);
        zvGroups.removeAllViews();
        for (String data : datas) {
            if (data.equals("")) {
                return;
            }
            //添加分类块
            View paramItemView = getLayoutInflater().inflate(R.layout.item_search, null);
            RelativeLayout rl_text = paramItemView.findViewById(R.id.rl_text);
            TextView keyWordTv = paramItemView.findViewById(R.id.tv_content);
            keyWordTv.setText("#" + data + "#");
            zvGroups.addView(paramItemView, layoutParams);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && data != null) {
            imgSelected.clear();
            imgSelected.addAll(Objects.requireNonNull(data.getStringArrayListExtra(ImageSelector.SELECT_RESULT)));
            boolean isCameraImage = data.getBooleanExtra(ImageSelector.IS_CAMERA_IMAGE, false);
//            Log.d("ImageSelector", "是否是拍照图片：" + isCameraImage);
            photoPublishAdapter.setData(imgSelected);
            fixBottom();
        } else if (requestCode == 222 && resultCode == RESULT_OK && data != null) {
            groups_select = data.getStringArrayListExtra("groups");
            if (groups_select != null) {
                initHistory(groups_select);
            }
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.photo_publish;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
